package com.lry.pda.bottom.demo;

import com.lry.pda.Lexer;
import com.lry.pda.topdown.SymbolDefine;

import java.util.Stack;

public class LRParser {

    private Lexer lexer;
    private Stack<Integer> stack = new Stack<>();//存储节点编号的状态堆栈
    private LRParserTable lrParserTable = new LRParserTable();
    private int inputToken;

    public LRParser(Lexer lexer){
        this.lexer = lexer;
        this.lexer.input();
        this.lexer.advance();
        this.inputToken = this.lexer.lookAhead;
        stack.push(0);//初始为0节点
    }


    public void parse(){
        LRParserTable.STATE_MACHINE_ACTION action = null;
        while(true){
            action = lrParserTable.getAction(stack.peek(),inputToken);

            switch (action){
                case accept:
                    System.out.println("can accept");
                    return;
                case error:
                    System.out.println("error");
                    return;
                case s1:
                    stack.push(1);
                    lexer.advance();
                    inputToken = lexer.lookAhead;
                    break;
                case s4:
                    stack.push(4);
                    lexer.advance();
                    inputToken = lexer.lookAhead;
                    break;

                    //expr -> expr+term
                case r1:
                    stack.pop();
                    stack.pop();
                    stack.pop();
                    inputToken = SymbolDefine.EXPR;
                    break;

                    //expr -> term
                case r2:
                    stack.pop();
                    inputToken = SymbolDefine.EXPR;
                    break;

                    //term -> num
                case r3:
                    stack.pop();
                    inputToken = SymbolDefine.TERM;
                    break;

                case state_2:
                    stack.push(2);
                    inputToken = lexer.lookAhead;
                    break;
                case state_3:
                    stack.push(3);
                    inputToken = lexer.lookAhead;
                    break;
                case state_5:
                    stack.push(5);
                    inputToken = lexer.lookAhead;
                    break;
            }
        }
    }

    public static void main(String[] args) {
        LRParser lrParser = new LRParser(new Lexer());
        lrParser.parse();
    }
}
